<template>
  <view class="order-confirm-container">
    <!-- 顶部导航栏 -->
    <view class="header">
      <view class="back-btn" @click="goBack">
        <text class="back-icon">‹</text>
      </view>
      <view class="header-title">订单确认</view>
      <view class="header-actions">
        <text class="action-icon">⋯</text>
      </view>
    </view>

    <!-- 订单信息 -->
    <view class="order-info-section">
      <view class="section-title">订单信息</view>
      <view class="order-item">
        <view class="item-left">
          <text class="item-icon">📦</text>
                  <view class="item-details">
          <text class="item-title">快递代取</text>
          <text class="item-desc">{{ expressData ? `${expressData.pickupLocation} → ${expressData.deliveryAddress}` : '西院篮球场 → 宿舍' }}</text>
        </view>
        </view>
        <view class="item-right">
          <text class="item-price">¥{{ baseFee.toFixed(2) }}</text>
        </view>
      </view>
    </view>

    <!-- 费用明细 -->
    <view class="fee-section">
      <view class="section-title">费用明细</view>
      
      <!-- 平台优惠券 -->
      <view class="fee-row" @click="selectCoupon">
        <view class="fee-left">
          <view class="fee-icon coupon-icon">券</view>
          <text class="fee-label">平台优惠券</text>
        </view>
        <view class="fee-right">
          <text class="fee-value" :class="{ 'placeholder': !selectedCoupon }">
            {{ selectedCoupon || '无可用券' }}
          </text>
          <text class="arrow-icon">›</text>
        </view>
      </view>

      <!-- 基础配送费 -->
      <view class="fee-row">
        <view class="fee-left">
          <text class="fee-label">基础配送费</text>
        </view>
        <view class="fee-right">
          <text class="fee-value">{{ deliveryFee.toFixed(2) }}</text>
        </view>
      </view>

      <!-- 小费加价 -->
      <view class="fee-row">
        <view class="fee-left">
          <text class="fee-label">小费加价</text>
        </view>
        <view class="fee-right">
          <text class="fee-value">{{ tipAmount.toFixed(2) }}</text>
          <view class="tip-buttons">
            <button 
              v-for="tip in tipOptions" 
              :key="tip"
              :class="['tip-btn', { active: tipAmount === tip }]"
              @click="selectTip(tip)"
            >
              +{{ tip }}
            </button>
          </view>
        </view>
      </view>
    </view>

    <!-- 其他选项 -->
    <view class="options-section">
      <view class="section-title">其他选项</view>
      
      <!-- 骑手性别 -->
      <view class="option-row" @click="selectRiderGender">
        <view class="option-left">
          <text class="option-label">骑手性别</text>
        </view>
        <view class="option-right">
          <text class="option-value">{{ riderGender }}</text>
          <text class="arrow-icon">›</text>
        </view>
      </view>

      <!-- 更多要求 -->
      <view class="option-row">
        <view class="option-left">
          <text class="option-label">更多要求</text>
        </view>
        <view class="option-right">
          <switch 
            :checked="moreRequirements" 
            @change="toggleMoreRequirements"
            color="#f44336"
          />
        </view>
      </view>
    </view>

    <!-- 费用总计 -->
    <view class="total-section">
      <view class="total-row">
        <text class="total-label">费用总计</text>
        <text class="total-amount">¥{{ totalAmount.toFixed(2) }}</text>
      </view>
    </view>

    <!-- 底部确认按钮 -->
    <view class="bottom-actions">
      <button class="confirm-btn" @click="confirmOrder">
        <text class="confirm-text">确认</text>
      </button>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { createExpressPickupOrder } from '@/api/express-pickup'
import type { ExpressPickupRequest } from '@/types/api/express-pickup'
import { getTipOptions } from '@/config/pricing'

// 响应式数据
const baseFee = ref(2.00)
const deliveryFee = ref(3.00)
const tipAmount = ref(0)
const selectedCoupon = ref('')
const riderGender = ref('不限性别')
const moreRequirements = ref(false)

// 快递代取数据
const expressData = ref<any>(null)

// 小费选项
const tipOptions = getTipOptions()

// 页面加载时接收传递的数据
onMounted(() => {
  const eventChannel = getOpenerEventChannel()
  eventChannel.on('expressData', (data) => {
    expressData.value = data
    // 更新基础费用
    baseFee.value = data.baseFee || 2.00
  })
})

// 计算属性
const totalAmount = computed(() => {
  return baseFee.value + deliveryFee.value + tipAmount.value
})

// 方法
const goBack = () => {
  uni.navigateBack()
}

const selectCoupon = () => {
  const coupons = ['无可用券', '满10减2', '满20减5', '新用户立减3元']
  uni.showActionSheet({
    itemList: coupons,
    success: (res) => {
      selectedCoupon.value = coupons[res.tapIndex]
    }
  })
}

const selectTip = (tip: number) => {
  tipAmount.value = tip
}

const selectRiderGender = () => {
  const genderOptions = ['不限性别', '男骑手', '女骑手']
  uni.showActionSheet({
    itemList: genderOptions,
    success: (res) => {
      riderGender.value = genderOptions[res.tapIndex]
    }
  })
}

const toggleMoreRequirements = (e: any) => {
  moreRequirements.value = e.detail.value
}

const confirmOrder = async () => {
  // 验证必填项
  if (!selectedCoupon && selectedCoupon !== '无可用券') {
    uni.showToast({
      title: '请选择优惠券',
      icon: 'none'
    })
    return
  }

  if (!expressData.value) {
    uni.showToast({
      title: '订单数据不完整',
      icon: 'none'
    })
    return
  }

  // 准备提交数据
  const orderData: ExpressPickupRequest = {
    // 配送信息
    deliveryAddress: expressData.value.deliveryAddress,
    deliveryTime: expressData.value.deliveryTime,
    
    // 物品信息
    itemSize: expressData.value.itemSize,
    pickupCode: expressData.value.pickupCode,
    pickupLocation: expressData.value.pickupLocation,
    
    // 费用信息
    baseFee: baseFee.value,
    deliveryFee: deliveryFee.value,
    tipAmount: tipAmount.value,
    
    // 其他选项
    selectedCoupon: selectedCoupon.value,
    riderGender: riderGender.value,
    moreRequirements: moreRequirements.value,
    
    // 用户信息（这里可以从用户store获取）
    userId: 'user123', // 实际应该从用户登录状态获取
    userName: '张三',   // 实际应该从用户登录状态获取
    userPhone: '138****8888' // 实际应该从用户登录状态获取
  }

  try {
    // 显示加载提示
    uni.showLoading({
      title: '提交中...'
    })

    // 调用后端API
    const response = await createExpressPickupOrder(orderData)
    
    uni.hideLoading()
    
    if (response.success) {
      uni.showToast({
        title: '订单提交成功',
        icon: 'success'
      })
      
      // 显示订单信息
      uni.showModal({
        title: '订单创建成功',
        content: `订单号：${response.data.orderNo}\n总金额：¥${response.data.totalAmount.toFixed(2)}`,
        showCancel: false,
        success: () => {
          // 跳转到订单页面
          uni.switchTab({
            url: '/pages/orders/orders'
          })
        }
      })
    } else {
      uni.showToast({
        title: response.message || '订单提交失败',
        icon: 'none'
      })
    }
  } catch (error) {
    uni.hideLoading()
    console.error('提交订单失败:', error)
    uni.showToast({
      title: '网络错误，请重试',
      icon: 'none'
    })
  }
}
</script>

<style scoped>
.order-confirm-container {
  background-color: #f5f5f5;
  min-height: 100vh;
  padding-bottom: 120rpx;
}

/* 顶部导航栏 */
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 30rpx;
  background-color: #fff;
  border-bottom: 1rpx solid #eee;
}

.back-btn {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.back-icon {
  font-size: 40rpx;
  color: #333;
}

.header-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.header-actions {
  width: 60rpx;
}

.action-icon {
  font-size: 32rpx;
  color: #666;
}

/* 内容区域 */
.order-info-section,
.fee-section,
.options-section,
.total-section {
  margin: 20rpx;
  background-color: #fff;
  border-radius: 20rpx;
  padding: 30rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 30rpx;
}

/* 订单信息 */
.order-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 0;
}

.item-left {
  display: flex;
  align-items: center;
  gap: 20rpx;
}

.item-icon {
  font-size: 40rpx;
}

.item-details {
  display: flex;
  flex-direction: column;
  gap: 10rpx;
}

.item-title {
  font-size: 30rpx;
  color: #333;
  font-weight: 500;
}

.item-desc {
  font-size: 26rpx;
  color: #666;
}

.item-price {
  font-size: 32rpx;
  color: #f44336;
  font-weight: bold;
}

/* 费用行 */
.fee-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 25rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
}

.fee-row:last-child {
  border-bottom: none;
}

.fee-left {
  display: flex;
  align-items: center;
  gap: 20rpx;
}

.fee-icon {
  width: 40rpx;
  height: 40rpx;
  border-radius: 8rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24rpx;
  color: #fff;
}

.coupon-icon {
  background-color: #ff9800;
}

.fee-label {
  font-size: 30rpx;
  color: #333;
}

.fee-right {
  display: flex;
  align-items: center;
  gap: 15rpx;
}

.fee-value {
  font-size: 28rpx;
  color: #333;
}

.fee-value.placeholder {
  color: #999;
}

.arrow-icon {
  font-size: 24rpx;
  color: #ccc;
}

/* 小费按钮 */
.tip-buttons {
  display: flex;
  gap: 10rpx;
}

.tip-btn {
  padding: 8rpx 16rpx;
  border: 1rpx solid #ddd;
  border-radius: 20rpx;
  background-color: #fff;
  color: #666;
  font-size: 24rpx;
  min-width: 60rpx;
}

.tip-btn.active {
  background-color: #f44336;
  color: #fff;
  border-color: #f44336;
}

/* 选项行 */
.option-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 25rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
}

.option-row:last-child {
  border-bottom: none;
}

.option-left {
  display: flex;
  align-items: center;
}

.option-label {
  font-size: 30rpx;
  color: #333;
}

.option-right {
  display: flex;
  align-items: center;
  gap: 15rpx;
}

.option-value {
  font-size: 28rpx;
  color: #666;
}

/* 费用总计 */
.total-section {
  margin-top: 40rpx;
}

.total-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 0;
}

.total-label {
  font-size: 32rpx;
  color: #333;
  font-weight: 500;
}

.total-amount {
  font-size: 36rpx;
  color: #f44336;
  font-weight: bold;
}

/* 底部按钮 */
.bottom-actions {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 20rpx;
  background-color: #fff;
  border-top: 1rpx solid #eee;
}

.confirm-btn {
  width: 100%;
  height: 88rpx;
  background-color: #f44336;
  color: #fff;
  border: none;
  border-radius: 10rpx;
  font-size: 32rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.confirm-text {
  font-size: 32rpx;
  font-weight: 500;
}
</style>
